package com.work.formaldehyde.activity;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activityadapter.AddressManageAdapter;
import com.work.formaldehyde.activityadapter.CityManageAdapter;
import com.work.formaldehyde.activityadapter.GouWuCheAdapter;
import com.work.formaldehyde.model.GetAddressModel;
import com.work.formaldehyde.model.GouWuCheModel;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class GetAddressActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private ImageView city_comeback;
    private RelativeLayout submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 0);
        setContentView(R.layout.activity_getaddress);
        city_comeback = findViewById(R.id.city_comeback);
        city_comeback.setOnClickListener(this);
        if (ApiUtils.isNetworkConnected(GetAddressActivity.this))
            inti();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private ArrayList<GetAddressModel.data> new_list_view;
    private ListView city_manage_list;
    public AddressManageAdapter myAdapter;
    private GetAddressModel getAddressModel;
    public static boolean isboole = false;

    /**
     * 初始加载视图
     */
    public void Init() {
        city_manage_list = findViewById(R.id.city_manage_list);
        new_list_view = new ArrayList<>();
        okHttp_postFromParameters();
        city_manage_list.setOnItemClickListener(this);
        city_manage_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                windows(GetAddressActivity.this, new_list_view.get(position).getId());
                return false;
            }
        });
        submit = findViewById(R.id.submit);
        submit.setOnClickListener(this);
    }

    /**
     * 初始化加载调用方法
     */
    public void inti() {
        Init();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!Url.USER_ID.equals("") && ApiUtils.isNetworkConnected(GetAddressActivity.this) && isboole) {
            ApiUtils.windows(GetAddressActivity.this, city_comeback, "请稍后");
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    ApiUtils.closepopup();
                }
            }, 10000);
            okHttp_postFromParameters();
            isboole = false;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.city_comeback:
                onBackPressed();
                break;
            case R.id.submit:
                if (Url.USER_ID.equals("")) {
                    Intent is_login = new Intent(GetAddressActivity.this, LoginActivity.class);
                    startActivity(is_login, ActivityOptions.makeSceneTransitionAnimation(GetAddressActivity.this).toBundle());
                    ApiUtils.SetToast(GetAddressActivity.this, "请先登录");
                } else {
                    Intent toaddress = new Intent(GetAddressActivity.this, AddressActivity.class);
                    toaddress.putExtra("opentype", "0");
                    startActivity(toaddress, ActivityOptions.makeSceneTransitionAnimation(GetAddressActivity.this).toBundle());
                }
                break;
        }
    }

    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN)
//                            .build();
//                    Request request = new Request.Builder().url(Url.GETADDRESSLIST).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot1.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.GETADDRESSLIST + "?uid=" + Url.USER_ID + "&logintoken=" + Url.LOGIN_TOKEN).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot1.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethot1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        getAddressModel = gson.fromJson(msg.obj.toString(),
                                GetAddressModel.class);
                        new_list_view.clear();
                        new_list_view.addAll(getAddressModel.getData());
                        myAdapter = new AddressManageAdapter(new_list_view,
                                GetAddressActivity.this, GetAddressActivity.this);
                        city_manage_list.setAdapter(myAdapter);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (i == (new_list_view.size() - 1)) {
        }
    }


    private PopupWindow popupWindows;
    private String citys = "";


    public void windows(Context context, final String city) {
        View popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popup_addresslist, null);
        RelativeLayout dangqian = popupwindowviews.findViewById(R.id.dangqian);
        dangqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ApiUtils.windows(GetAddressActivity.this, city_comeback, "请稍后");
                okHttp_postFromParameters1(city);
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        ApiUtils.closepopup();
                    }
                }, 10000);
                citys = city;
                popupWindows.dismiss();
            }
        });
        RelativeLayout jieshu = popupwindowviews.findViewById(R.id.jieshu);
        jieshu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindows.dismiss();
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setAnimationStyle(R.style.popwin_anim_style);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
        popupWindows.showAtLocation(city_manage_list, Gravity.BOTTOM, 0, 0);
    }

    private void okHttp_postFromParameters1(final String addrid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("addrid", addrid)
                            .build();
                    Request request = new Request.Builder().url(Url.DELADDRESS).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot1s.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethot1s = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                ApiUtils.SetLog("del=" + msg.obj.toString());
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        ApiUtils.windows(GetAddressActivity.this, city_comeback, "请稍后");
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                ApiUtils.closepopup();
                            }
                        }, 10000);
                        okHttp_postFromParameters();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
